// import router from '@/lib/router';
import Vue from 'vue';
import Router from 'vue-router';
import { setToken, setCookieTenant, getUserToken, setCurrentOU, getLocalToken } from '@/lib/auth'; // get token from cookie
import { Message } from 'element-ui';

Vue.use(Router);
import extendRouter from './module/index';

const createRouter = (aRouterList) => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: aRouterList
});

const whiteList = ['/404', '/appPayBefore', '/appPayAfter', '/privacy'];

const router = createRouter(extendRouter);
// 路由跳转检测
router.beforeEach(async (to, from, next) => {
  if (to.query.token) {
    setToken(to.query.token);
  }
  if (to.query.currentOU) {
    setCurrentOU(to.query.currentOU);
  }
  if (to.query.tenantid) {
    let tenantId = to.params.id
      ? to.params.id.lastIndexOf('_') > -1 && to.params.id.split('_')[1] !== 'plat'
        ? to.params.id.split('_')[1]
        : ''
      : '';
    tenantId = tenantId || to.query.tenantid;
    setCookieTenant(tenantId);
  }

  const hasToken = getLocalToken() || await getUserToken();
  console.log(hasToken);
  if (hasToken) {
    next();
  } else {
    if (!testWhiteList(whiteList, to.path)) {
      Message({
        type: 'warning',
        message: '未登录，请登陆'
      });
      next({ path: '/404', replace: true });
    } else {
      next();
    }
  }
});

export function testWhiteList (whiteList, path) {
  if (!whiteList) {
    return false;
  }
  if (whiteList.includes(path)) {
    return true;
  }
  for (const i in whiteList) {
    if (typeof whiteList[i] !== 'string') {
      if (whiteList[i].test(path)) {
        return true;
      }
    }
  }
  return false;
}

export default router;
